#include "myserver.h"
#include "ui_myserver.h"
#include <QHostAddress>
#include <QDebug>

myserver::myserver(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::myserver)
{
    ui->setupUi(this);

    //1.分配内存
    this->server = new QTcpServer(this);

    //2.监听
    this->server->listen(QHostAddress::Any, 1688);

    //3.关联链接请求信号，如有连接则跳到自定义槽函数
    QObject::connect(this->server, SIGNAL(newConnection()), this, SLOT(new_connect()));

}

myserver::~myserver()
{
    delete ui;
}

//新连接槽函数
void myserver::new_connect()
{
    QString port, ip, ip_port;
    //1.通信套接字内存申请
    this->client = new QTcpSocket(this);;

    //2.新连接
    this->client = this->server->nextPendingConnection();

    //3.获取客户端IP及端口号
    ip = this->client->peerAddress().toString();
    port = QString::number(this->client->peerPort());
    ip_port = ip + ":" + port;
    ip_port = ip_port.remove(0, 7);//客户端IP及端口号
    qDebug()<<"有新连接 地址信息是"<<ip_port;

    //4.绑定信息接收信号机槽函数，如有信息发来则跳到自定义槽函数
    QObject::connect(this->client, SIGNAL(readyRead()),this,SLOT(receive_data()));

    //5.给客户端发送数据
    QString msg  = "你好，我是服务器端";
    this->client->write(msg.toUtf8());
}

//数据接收槽函数
void myserver::receive_data()
{
    QString msg  = this->client->readAll();
    qDebug()<<"服务器有数据可读, 数据是 "<<msg;
}
